package com.tim.app.ui.adapter.search;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.roundimg.RoundedImageView;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.AppKey;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.ActionStateMsg;
import com.tim.app.server.entry.User;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.FollowResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.SearchActivity;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.TextUtil;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.List;


/**
 * 用户搜索
 */
public class SearchUserAdapter extends BaseRecyclerAdapter<BaseRecyclerAdapter.BaseRecyclerViewHolder, User> {

    private Context mContext;

    private String keyWord = "";

    public SearchUserAdapter(Context mContext, List<User> mDataList) {
        super(mDataList);
        this.mContext = mContext;
    }

    public String getKeyWord() {
        return keyWord;
    }

    public void setKeyWord(String keyWord) {
        this.keyWord = keyWord;
    }

    @Override
    public BaseRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        BaseRecyclerViewHolder holder = null;
        holder = new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_search_user, parent, false));
        return holder;
    }

    @Override
    public void onBindViewHolder(BaseRecyclerViewHolder mHolder, final int position, final User data) {
        if (data == null) {
            return;
        }
        final ViewHolder holder = (ViewHolder) mHolder;
        if (!TextUtils.isEmpty(data.getImage())) {
            BitmapLoader.ins().loadImage(data.getImage(), holder.rivAvatar);
        }
        if (!TextUtils.isEmpty(data.getName())) {
            TextUtil.setTextHighLight(holder.tvUserName, getKeyWord(), data.getName());
        } else {
            holder.tvUserName.setText("");
        }
        if (!TextUtils.isEmpty(data.getIntroduce())) {
            TextUtil.setTextHighLight(holder.tvUserDesc, getKeyWord(), data.getIntroduce());
        } else {
            holder.tvUserDesc.setText("个人签名");
        }
        holder.tvLevel.setText(mContext.getString(R.string.userLevel, String.valueOf(data.getLevelId())));
        if (data.getSex() == 1) {
            Drawable manDrawable = mContext.getResources().getDrawable(R.drawable.ic_male);
            manDrawable.setBounds(0, 0, manDrawable.getMinimumWidth(), manDrawable.getMinimumHeight());
            holder.tvInfo.setCompoundDrawables(manDrawable, null, null, null);
            holder.tvInfo.setCompoundDrawablePadding((int) RT.getDensity() * 1);
            holder.tvInfo.setSelected(false);
        } else if (data.getSex() == 2) {
            Drawable manDrawable = mContext.getResources().getDrawable(R.drawable.ic_female);
            manDrawable.setBounds(0, 0, manDrawable.getMinimumWidth(), manDrawable.getMinimumHeight());
            holder.tvInfo.setCompoundDrawables(manDrawable, null, null, null);
            holder.tvInfo.setCompoundDrawablePadding((int) RT.getDensity() * 1);
            holder.tvInfo.setSelected(true);
        }
        holder.tvInfo.setText(String.valueOf(data.getAge()));

        holder.tvSearchFollowNumber.setText(mContext.getString(R.string.searchFollowNumber, String.valueOf(data.getConcernUserCount())));
        holder.tvSearchPriseNumber.setText(mContext.getString(R.string.searchPriseNumber, String.valueOf(data.getAgreeCount())));
        if (UserManager.ins().isLogin() && UserManager.ins().getUserId().equals(data.getId())) {
            holder.tvFollow.setVisibility(View.GONE);
        } else {
            holder.tvFollow.setVisibility(View.VISIBLE);
        }
        if (null != data.getActionStateMsg()) {
            if (null != data.getActionStateMsg().getUserState()) {
                holder.tvFollow.setSelected(true);
                holder.tvFollow.setText(R.string.hasFollow);
            } else {
                holder.tvFollow.setSelected(false);
                holder.tvFollow.setText(R.string.unFollow);
            }
        }

        holder.tvFollow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(mContext);
                    return;
                }
                followOrCancelFollow(holder.tvFollow, position, data);
            }
        });
        if (position != getDataList().size() - 1) {
            holder.vLine.setVisibility(View.VISIBLE);
        } else {
            holder.vLine.setVisibility(View.GONE);
        }
    }

    /**
     * 关注/取消关注
     */
    private void followOrCancelFollow(final View view, final int position, final User data) {
        view.setEnabled(false);
        if (null != data.getActionStateMsg() && data.getActionStateMsg().getUserState() != null) {
            int id = data.getActionStateMsg().getUserState();
            API_User.ins().cancelFollow(SearchActivity.TAG, id, UserManager.ins().getUserId(), data.getId(), AppKey.TYPE_USER, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    view.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        getDataList().get(position).getActionStateMsg().setUserState(null);
                        notifyItemChanged(position);
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        } else {
            API_User.ins().addFollow(SearchActivity.TAG, UserManager.ins().getUserId(), data.getId(), AppKey.TYPE_USER, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    view.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        FollowResult result = new Gson().fromJson(resultValue, FollowResult.class);
                        if (null != result && null != result.getRes()) {
                            if (getDataList().get(position).getActionStateMsg() == null) {
                                getDataList().get(position).setActionStateMsg(new ActionStateMsg());
                            }
                            getDataList().get(position).getActionStateMsg().setUserState(result.getRes().getConcern().getId());
                            notifyItemChanged(position);
                        }
                    } else if (ResponseResult.ResultStatus.BE_ADD_BLACK == errCode) {
                        if (data.getSex() == AppKey.SEX_MAN) {
                            ToastUtil.showToast("由于对方的设置，你不能关注他");
                        } else {
                            ToastUtil.showToast("由于对方的设置，你不能关注她");
                        }
                    }else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        }
    }

    public class ViewHolder extends BaseRecyclerViewHolder {

        RoundedImageView rivAvatar;
        ImageView ivVip;
        TextView tvInfo, tvLevel;
        TextView tvUserName;
        TextView tvUserDesc;
        TextView tvFollow;
        View vLine;
        TextView tvSearchFollowNumber;
        TextView tvSearchPriseNumber;

        public ViewHolder(View itemView) {
            super(itemView);
            rivAvatar = (RoundedImageView) itemView.findViewById(R.id.rivAvatar);
            tvUserName = (TextView) itemView.findViewById(R.id.tvUserName);
            tvLevel = (TextView) itemView.findViewById(R.id.tvLevel);
            ivVip = (ImageView) itemView.findViewById(R.id.ivVip);
            tvInfo = (TextView) itemView.findViewById(R.id.tvInfo);
            tvUserDesc = (TextView) itemView.findViewById(R.id.tvUserDesc);
            tvFollow = (TextView) itemView.findViewById(R.id.tvFollow);
            vLine = itemView.findViewById(R.id.vLine);
            tvSearchFollowNumber = (TextView) itemView.findViewById(R.id.tvSearchFollowNumber);
            tvSearchPriseNumber = (TextView) itemView.findViewById(R.id.tvSearchPriseNumber);
        }

    }

}
